from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_http_methods
import json
from datetime import datetime, timedelta
from django.utils import timezone

from api.logic.wechat import WechatLogic
from ..utils.jwt_utils import verify_token
from ..utils.response import success_response, error_response
from ..utils.log_utils import log_operation
from ..models.vip import VipActivationCode, VipMember
from django.contrib.auth.models import User

@csrf_exempt
@require_http_methods(["POST"])
def vip_activate(request):
    """激活VIP"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        # 获取用户信息
        wechat_logic = WechatLogic()
        user = wechat_logic.get_user_by_token(token)
        user_id = user.id
        if not user:
            return error_response('未登录或登录已过期')
            
        # 解析请求数据
        data = json.loads(request.body)
        code = data.get('code')
        
        if not code:
            return error_response('激活码不能为空')
            
        # 获取用户信息
        # user = User.objects.get(id=user_id)
        
        # 查找激活码
        try:
            activation_code = VipActivationCode.objects.get(code=code)
        except VipActivationCode.DoesNotExist:
            return error_response('无效的激活码')
            
        # 检查激活码是否已使用
        if activation_code.is_used:
            return error_response('该激活码已被使用')
            
        # 检查激活码是否过期
        if activation_code.expired_at and activation_code.expired_at < timezone.now():
            return error_response('该激活码已过期')
            
        # 获取或创建VIP会员记录
        vip_member, created = VipMember.objects.get_or_create(
            user=user,
            defaults={
                'vip_type': activation_code.vip_type,
                'start_time': timezone.now()
            }
        )
        
        # 计算VIP到期时间
        if activation_code.vip_type == 'lifetime':
            end_time = None
        else:
            duration_days = 30 if activation_code.vip_type == 'month' else 365
            if vip_member.end_time and vip_member.end_time > timezone.now():
                # 如果当前会员未过期，在现有结束时间基础上增加时长
                end_time = vip_member.end_time + timedelta(days=duration_days)
            else:
                # 如果当前会员已过期或不存在，从当前时间开始计算
                end_time = timezone.now() + timedelta(days=duration_days)
                
        # 更新VIP会员信息
        vip_member.vip_type = activation_code.vip_type
        vip_member.end_time = end_time
        vip_member.is_active = True
        vip_member.save()
        
        # 标记激活码为已使用
        activation_code.is_used = True
        activation_code.used_by = user
        activation_code.used_at = timezone.now()
        activation_code.save()
        
        # 记录操作
        log_operation(user, 'activate_vip', f'使用激活码开通VIP: {code}')
        
        return success_response({
            'vip_type': vip_member.vip_type,
            'vip_type_display': vip_member.get_vip_type_display(),
            'start_time': vip_member.start_time.strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': vip_member.end_time.strftime('%Y-%m-%d %H:%M:%S') if vip_member.end_time else None,
            'is_active': vip_member.is_active
        })
    except User.DoesNotExist:
        return error_response('用户不存在')
    except Exception as e:
        return error_response(str(e))

@require_http_methods(["GET"])
def vip_info(request):
    """获取VIP信息"""
    try:
        # 验证token
        token = request.headers.get('Authorization')
        if not token:
            return error_response('未提供token', 401)
        
        # 获取用户信息
        wechat_logic = WechatLogic()
        user = wechat_logic.get_user_by_token(token)
        user_id = user.id
        if not user_id:
            return error_response('未登录或登录已过期')
            
        # 获取用户信息
        # user = User.objects.get(id=user_id)
        
        # 获取VIP会员信息
        try:
            vip_member = VipMember.objects.get(user=user)
            # 检查VIP状态
            is_active = vip_member.check_vip_status()
            if not is_active and vip_member.is_active:
                vip_member.is_active = False
                vip_member.save()
        except VipMember.DoesNotExist:
            return success_response({
                'is_vip': False,
                'vip_type': None,
                'vip_type_display': None,
                'start_time': None,
                'end_time': None
            })
            
        return success_response({
            'is_vip': vip_member.is_active,
            'vip_type': vip_member.vip_type,
            'vip_type_display': vip_member.get_vip_type_display(),
            'start_time': timezone.localtime(vip_member.start_time).strftime('%Y-%m-%d %H:%M:%S'),
            'end_time': timezone.localtime(vip_member.end_time).strftime('%Y-%m-%d %H:%M:%S') if vip_member.end_time else None
        })
    except User.DoesNotExist:
        return error_response('用户不存在')
    except Exception as e:
        return error_response(str(e)) 